<?php
namespace App\Common\Cla\Com\Token;

use App\Common as com;

class DataId extends TokenBase {
	use TraitKeyDbOperate;

	/**
	 * 获取Token->DataId缓存键对象
	 * @return com\Lib\Cache\KeyDB
	 */
	public function keyDbObj(  ) {
		if( $this->_keyDbObj === null ){
			$this->_keyDbObj = com\Lib\Cache\KeyDB::use( 'reb.open.v1.api.token.dataId' )->param( $this->tokenObj->data()->getDataId() );
		}
		return $this->_keyDbObj;
	}

	/**
	 * 获取token
	 * @return string
	 */
	public function getToken(  ) {
		$data = $this->getOfPath( 'token', null );
		if( null === $data ) throw com\Lib\Err\Exception::makeOfNew( '', com\Lib\Err\Code::$sysDataError );
		return $data;
	}

	/**
	 * 设置token
	 * @param $tokenStr
	 */
	public function setToken( $tokenStr ) {
		$this->setOfPath( 'token', $tokenStr );
	}

	/**
	 * 加入关联缓存列表
	 * @param string $cacheKey 缓存名
	 */
	public function addRelevanceKey( string $cacheKey ) {
		$relevanceKeys = $this->getOfPath( 'relevanceKey', [] );
		if( ! in_array( $cacheKey, $relevanceKeys ) ){
			$relevanceKeys[] = $cacheKey;
		}
		//
		$this->setOfPath( 'relevanceKey', $relevanceKeys );
	}


	/**
	 * 刷新列表中的ttl
	 * @param int $expire 有效时间。[null]跟随原数据剩余时间 [>0]时间
	 */
	public function refreshTtlOfRelevanceKeys( int $expire = null ) {
		$relevanceKeys = $this->getOfPath( 'relevanceKey', [] );
		$expireMid = $expire ?? $this->tokenObj->data()->getSupTime();
		foreach( $relevanceKeys as $key ){
			com\Lib\Cache\KeyDB::use( $key )->setTtl( $expireMid );
		}
	}

	/**
	 * 读取数据剩余时间
	 * @return int 剩余时间戳
	 */
	/*
	public function getSupTime(  ):int {
		$supTime = $this->getCacheOfPath( 'expireTime', 0 ) - com\Lib\Fun\Time::getTime();
		if( $supTime < 0 ) $supTime = 0;
		//
		return $supTime;
	}
	*/
}
